package com.cljz.makepassenger.present.activity;

import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.base.BaseP;
import com.cljz.makepassenger.base.Constant;
import com.cljz.makepassenger.model.net.api.Api;
import com.cljz.makepassenger.model.net.bean.SetUserInfoBean;
import com.cljz.makepassenger.ui.activity.MineActivity;
import com.clzj.makepassenger.bean.UserInfo;

import java.util.Map;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.net.ApiSubcriber;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.net.diy.Base64Utils;
import okhttp3.RequestBody;

/**
 * Created by apple on 2017/4/11.
 */

public class MineP extends BaseP<MineActivity> {
    public enum UpUserInfo {
        SEX, BIRTHDAY
    }

    public void getUserMsgUp(final Map<String, String> userInfoMap, final UpUserInfo userInfo) {
        String body = Base64Utils.enCode(gson.toJson(userInfoMap));
        final RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("text/plain;charset=UTF-8"), body);
        Api.getResponseInfoAPI().setUserInfoData(requestBody)
                .compose(XApi.<SetUserInfoBean>getApiTransformer())         //异常处理
                .compose(XApi.<SetUserInfoBean>getScheduler())              //线程切换
                .compose(getV().<SetUserInfoBean>bindToLifecycle())
                .subscribe(new ApiSubcriber<SetUserInfoBean>() {
                    @Override
                    protected void onFail(NetError error) {
                    }

                    @Override
                    public void onNext(SetUserInfoBean setUserInfoBean) {
                        if ("0".equals(setUserInfoBean.getError_code())) {
                            intoDB(setUserInfoBean.getData().getNewX(),userInfoMap, userInfo);
                            getV().userMsgUpSucceed(setUserInfoBean.getMsg());
                        } else if ("1000".equals(setUserInfoBean.getError_code())) {
                            getV().loginOvertime(1);
                        } else {
                            getV().userMsgUpFail(setUserInfoBean.getMsg());
                        }
                    }
                });
    }

    private void intoDB(String newToken,Map<String, String> userInfoMap, UpUserInfo upUserInfo) {
        UserInfo userInfo = getLocalUserInfo(getToken());
        SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, newToken);
        if (upUserInfo == UpUserInfo.SEX) {
            userInfo.setUser_sex(userInfoMap.get("user_sex"));
        } else if (upUserInfo == UpUserInfo.BIRTHDAY) {
            userInfo.setBirthday(userInfoMap.get("birthday"));
        }
        daoSession.getUserInfoDao().deleteAll();
        userInfo.setToken(newToken);
        daoSession.getUserInfoDao().insert(userInfo);
    }
}
